package com.sense.kukoo.common.wiget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import com.google.android.material.tabs.TabLayout
import com.sense.kukoo.common.R
import com.sense.kukoo.common.utils.ApplicationContext

class DescriptionTabLayout: TabLayout {

    private val TAG: String = javaClass.simpleName
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    companion object{
        val TYPE_DESCRIPTION = 0
        val TYPE_COMMENT = 1
    }

    private lateinit var mTitles: Array<String>

    private var mOnTabListener: (Int)->Unit = {}
    private val mCustomViews: ArrayList<View> = arrayListOf()
    private var mCaculateWidth = -1

    fun setOnTabListener(l: (Int)->Unit){
        mOnTabListener = l
    }

    private val mListener = object : OnTabSelectedListener {
        override fun onTabSelected(tab: Tab) {
            mOnTabListener(tab.position)
        }

        override fun onTabUnselected(tab: Tab) {}

        override fun onTabReselected(tab: Tab) {}
    }

    fun init(titles: Array<String>) {
        this.mTitles = titles
        //
        removeOnTabSelectedListener(mListener)
        addOnTabSelectedListener(mListener)
        removeAllTabs()
    }

    fun setTab(tab: Tab, position: Int) {
        tab.setCustomView(R.layout.common_item_tab_description)
        tab.customView?.let {
            mCustomViews.add(it)
            val tv_item_tab_text = it.findViewById<TextView>(R.id.tv_item_tab_text)
            //
            tv_item_tab_text.setText(mTitles.get(position))
        }
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        if(mCaculateWidth != width){
            mCaculateWidth = width
            resizeItem()
        }
    }

    fun resizeItem(){
        val size = if(mCustomViews.size > 0) mCustomViews.size else 1
        val childWidth = mCaculateWidth / size - ApplicationContext.dp2px(4F)
        mCustomViews.forEachIndexed { index, view ->
            val layoutParams = view.layoutParams
            layoutParams.width = childWidth
            view.layoutParams = layoutParams
        }
    }

}